import React, { useEffect, RefObject, useState } from "react";
import styles from "./index.module.scss";
import {
  Form,
  Input,
  Button,
  Dialog,
  Avatar,
  Toast,
  Skeleton,
  List,
} from "antd-mobile";
import dayjs from "dayjs";
import type { DatePickerRef } from "antd-mobile/es/components/date-picker";
// radio
import { Radio } from "antd-mobile";

// 路由
import { useNavigate } from "react-router-dom";

// 导入仓库
import {
  myUserToken,
  storeUser,
  changeIsLogin,
  changeUser,
  phoneOpenid,
} from "@/store/userSlice";

// 导入带有类型的属性，方法 1.
import { useAppDispatch, useAppSelector } from "../../hooks";

// 请求
import { ApiCheckLogin, ApiMemberCarList, ApiMemberInfo, ApiMemberUpdate } from "@/utils/api";

// 验证码
// import { ApiSendCaptcha,ApiRegister } from "@/utils/api";
import wxfetch from "@/utils/wxfetch";

// 加密解密
import crypt from "@/utils/crypto";


export default () => {
  // 表单更新
  // const [form] = Form.useForm();

  // 导入仓库 2.使用属性
  const userToken = useAppSelector(myUserToken);
  // const user = useAppSelector(storeUser);

  const myOpenid = useAppSelector(phoneOpenid);
  // 导入仓库 2.使用方法
  const dispatch = useAppDispatch();

  // 路由跳转
  const navigate = useNavigate();
  // 初始化检验是否注册
  // const checkUserInfo = async () => {
  //   // 是否已注册
  //   const encryptedUserInfo = localStorage.getItem("encryptedUserInfo");
  //   // 是否有accessToken
  //   // const encryptedUserToken = checkUserToken();
  //   if (encryptedUserInfo) {
  //     // 有
  //     // 判断是否过期
  //     console.log("已注册过", encryptedUserInfo);
  //   } else {
  //     console.log("未注册过");
  //     pushRegister();
  //   }
  // };

  // 去到注册页;
  const pushRegister = () => {
    // window.location.href = "http://127.0.0.1:8080";
    navigate("/register");
  };

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);

  // 会员车辆
  const [member, setMember] = useState<Datum["plate_number"][]>([]);

  // 骨架屏
  const [loading, setLoading] = useState(true);
  // 用户填写信息
  const [formData, setFormData] = useState({
    name: "",
    sex: 0,
    birthday: null,
    mobile: "",
    captcha: "",
    plate_number: "",
    // member: member,
    member_car_plate_number:''
  });

  // 请求登录状态
  // const checkLogin = async () => {
  //   console.log(userToken.openid, "openid");
  //   const res = await ApiCheckLogin(userToken.openid);
  //   if (res.code == 0) {
  //     //  存到仓库？
  //     console.log(res.data.member_id, "member_id");
  //     // 当前页面使用
  //     setMember_id(res.data.member_id);
  //     // getMemberInfo(res.data.member_id);
  //     return res.data.member_id;
  //   } else {
  //     console.log("未登录");
  //     return;
  //   }
  // };
  const checkLogin = async () => {
    if (!myOpenid) {
      // 去到注册页
      localStorage.removeItem("encryptedUserToken");
      navigate("/register");
      // console.error("/register");
    }
    console.log(myOpenid, "openid");
    // console.log(formData, "formData");
    // 暂时先用手机号+
    const res = await ApiCheckLogin(myOpenid);
    if (res.code == 0) {
      //  存到仓库？
      // console.log(res.data.member_id, "member_id");
      // 当前页面使用
      setMember_id(res.data.member_id);
      // await getMemberInfo(res.data.member_id);
      // 用于后续 获取会员详情信息
      console.log(res.data.member_id);
      await getMemberInfo(res.data.member_id);
      return res.data.member_id;
    } else {
      console.log("未登录");
      return;
    }
  };

  // 修改user对象属性值
  const handleFieldChange = <K extends keyof RootObject>(
    fieldName: K,
    value: RootObject[K]
  ) => {
    // console.log(fieldName, value);
    setFormData((prevData) => ({
      ...prevData,
      [fieldName]: value,
    }));
  };

  //  user对象里的属性名 属性值
  const handleNameInputChange = (
    type: keyof RootObject,
    value: RootObject[keyof RootObject]
  ) => {
    // console.log("type", type);
    handleFieldChange(type, value);
    // form.setFieldsValue(formData);
    // console.log("formData", formData);
  };

  // 获取会员详情信息
  const getMemberInfo = async (member_id2?: number) => {
    let my_member_id = member_id2 ? member_id2 : member_id;
    if (my_member_id == -1) {
      console.log("需重新进入");
      return;
    }
    // console.log(my_member_id, "my_member_id");
    // 请求用户信息
    const resInfo = await ApiMemberInfo(my_member_id);
    // console.log(resInfo, "resInfo");
    if (resInfo.code != 0) {
      console.log("请求用户信息失败");
      return;
    }
    // 成功
    // 更新用户对象
    const { name, mobile, sex, birthday, member_car_plate_number } =
      resInfo.data;
    // 更新
    handleNameInputChange("name", name);
    handleNameInputChange("mobile", mobile);
    handleNameInputChange("sex", sex);
    handleNameInputChange("birthday", new Date(birthday));
    handleNameInputChange("member_car_plate_number", member_car_plate_number);
    // form.setFieldsValue(formData);
    return resInfo;
  };

  // 表达提交事件
  const onFinish = (values: any) => {
    console.log("values", values);
    // Dialog.alert({
    //   content: <pre>{JSON.stringify(values, null, 2)}</pre>,
    // });
  };

  // 检查登录 获取member_id
  // const initData = async () => {
  //   const member_id = await checkLogin();
  //   if (!member_id) return;
  //   // 用于后续 获取会员详情信息
  //   await getMemberInfo(member_id);
  //   // 请求车牌号
  //   // getMemberCarList();
  //   // 根据openid获取用户信息
  //   await getUserInfo(userToken.access_token, userToken.openid);
  // };

  // 初始化
  const initDataFn = async () => {
    // 检测是否注册
    // await checkUserInfo();
    // 请求车辆列表
    try {
      await initData();
      // 请求车牌号 车辆详情
      // 二次处理
      // await mapMemberCarList();
    } finally {
      // 无论请求成功或失败，都设置 loading 为 false
      // 使用骨架屏
      setLoading(false);
    }
  };
  // 检查登录 获取member_id
  const initData = async () => {
    await checkLogin();
    // console.log(userToken.access_token, userToken.openid);

    // await getUserInfo(userToken.access_token, userToken.openid);
  };

  // 请求车牌号
  // 车辆详情 二次处理数据
  // const getMemberCarList = async () => {
  //   try {
  //     // 二次处理
  //     const res = await ApiMemberCarList();
  //     const data = res.data.map((item) => {
  //       return item.plate_number;
  //     });
  //     setMember(data);
  //   } finally {
  //     // 无论请求成功或失败，都设置 loading 为 false
  //     // 使用骨架屏
  //     setLoading(false);
  //   }
  //   // 显示第一项 更新表单
  // };
  // 获取userInfo
  const getUserInfo = async (access_token: string, openid: string) => {
    // 校验是否有openid和session_member_id
    if (!openid) {
      console.log("没有获取openid或没有校验登录");
      return;
    }
    const data = await wxfetch.getUserInfoFn(access_token, openid);
    if ("openid" in data) {
      await deterName(data);
    } else {
      // 请求失败，data 是 wxErrorInfo 类型
      navigate("/");
      console.error(data.errcode, data.errmsg);
    }
  };
  // const [wxImg, setWxImg] = useState(localStorage.getItem("img"));
  // 在页面加载时从localStorage获取图像数据
  const initialImg = localStorage.getItem("img") || "";
  const [img, setImg] = useState<string>(initialImg);
  // 图片上传
  const uploadImg = (e) => {
    const formdata = new FormData();
    formdata.append("headImg", e.target.files[0]);
    const file = formdata.get("headImg");

    if (file instanceof Blob) {
      const reader = new FileReader();

      reader.onload = function (event) {
        if (event.target) {
          const imageData = event.target.result;
          setImg(imageData as any);
          localStorage.setItem("img", imageData as any);
        }
      };

      reader.readAsDataURL(file);
    }
  };

  // 更新姓名性别
  const deterName = async (wxInfo: wxInfo) => {
    console.log(wxInfo.openid, "openid");
    // 校验是否有openid和session_member_id
    if (!wxInfo.openid) {
      console.log("没有获取openid或没有校验登录");
      return;
    }
    console.log(wxInfo.openid, "openid");
    const { headimgurl } = wxInfo;
    // 渲染页面
    // 更新用户对象
    if (!img) {
      setImg(headimgurl);
    }
  };

  // 修改其他
  const changeInfo = () => {
    navigate("/infochange");
  };
  const changeInfo2 = () => {};
  // 修改手机号
  const changePhone = () => {
    navigate("/phone");
  };

  // 挂载页面
  useEffect(() => {
    // checkUserInfo();
    // 检查登录 获取member_id
    initDataFn();
  }, []);
  // 挂载页面
  // useEffect(() => {
  //   // console.log(formData, "formData");
  //   form.setFieldsValue(formData);
  // }, [formData, form]);

  return (
    <div className={styles.form}>
      <Skeleton.Paragraph
        animated
        lineCount={8}
        style={{ display: loading ? "block" : "none" }}
      />
      {/* <div className="bg">
        <img src="../../assets/img/bg.png" alt="" />
        <div className="home_title">个人中心</div>
      </div> */}
      <List
        mode="card"
        header="会员信息"
        style={{ display: !loading ? "block" : "none" }}
      >
        <List.Item
          onClick={changeInfo2}
          extra={
            <>
              {/* <Avatar
                src={wxImg}
                style={{ "--size": "24px", "--border-radius": "50%" }}
              /> */}
              <div className="img">
                <input type="file" id="headImg" hidden onChange={uploadImg} />
                <label htmlFor="headImg">
                  <div
                    className="headImg"
                    id="headImg"
                    style={{ backgroundImage: `url(${img})` }}
                  ></div>
                </label>
              </div>
            </>
          }
          // onClick={uploadImg}
        >
          头像
        </List.Item>
        {/* <div className="img">
          <input type="file" id="headImg" hidden onChange={uploadImg} />
          <label htmlFor="headImg">
          <div
              className="headImg"
              id="headImg"
              style={{ backgroundImage: `url(${wxImg})` }}
            ></div>
          </label>
        </div> */}
        <List.Item extra={formData.name} onClick={changeInfo}>
          姓名
        </List.Item>
        <List.Item
          extra={formData.sex == 1 ? "男" : formData.sex == 2 ? "女" : "未知"}
          onClick={changeInfo}
        >
          性别
        </List.Item>
        <List.Item extra={formData.mobile} onClick={changePhone}>
          手机号
        </List.Item>
        <List.Item
          extra={
            formData.birthday
              ? dayjs(formData.birthday).format("YYYY-MM-DD")
              : "请选择日期"
          }
          onClick={changeInfo}
        >
          出生日期
        </List.Item>
        <List.Item
          extra={formData.member_car_plate_number}
          onClick={() => navigate("/memberCar")}
        >
          车牌号
        </List.Item>
      </List>
    </div>
  );
};
